package handler

import (
	"encoding/json"
	"fmt"
	"github.com/xiyoufang/cloud-syncer/internal/env"
	"github.com/xiyoufang/cloud-syncer/internal/http/model"
	"net/http"
)

// FileHandler 查看所有文件
func FileHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var req model.PaginateReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		env.Logger().Error(err.Error())
		http.Error(w, fmt.Sprintf("无效参数, 错误信息: %v", err), http.StatusBadRequest)
		return
	}
	var response model.ResponseBodyEntity
	if pageVO, err := env.Repository().GetFilesPaginate(req); err != nil {
		env.Logger().Error(err.Error())
		response = model.ResponseBodyEntity{
			Code:    model.InternalServerError,
			Message: err.Error(),
			Data:    pageVO,
		}
		return
	} else {
		response = model.ResponseBodyEntity{
			Code:    model.OK,
			Message: "success",
			Data:    pageVO,
		}
	}
	if err := json.NewEncoder(w).Encode(response); err != nil {
		env.Logger().Error(err.Error())
		http.Error(w, fmt.Sprintf("系统错误, 错误信息: %v", err), http.StatusInternalServerError)
		return
	}
}
